package com.tju.resource.server.impl;

import com.tju.resource.common.ServiceException;
import com.tju.resource.model.TbProdPlan;
import com.tju.resource.model.TbReportOrder;
import com.tju.resource.server.TbOrderService;
import com.tju.resource.server.TbProdPlanService;
import com.tju.resource.server.TbReportOrderService;
import com.tju.resource.server.TbStorageService;
import com.tju.resource.tool.result.Result;
import com.tju.resource.tool.result.ResultEnum;
import com.tju.resource.tool.result.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class TbStorageServiceImpl implements TbStorageService {
    @Autowired
    private TbOrderService orderService;
    @Autowired
    private TbProdPlanService tbProdPlanService;
    @Autowired
    private TbReportOrderService reportOrderService;

    /**
     * 审核入库
     *
     * @param reportOrder
     * @return
     */
    @Override
    @Transactional
    public Result<Object> approve(TbReportOrder reportOrder) {
        //成品数+半成品数
        reportOrder.setReportQty((int) (reportOrder.getQualify() + reportOrder.getDisQua()));
        TbProdPlan plan = new TbProdPlan();//生产计划
        plan.setId(reportOrder.getPpId()); //生产计划id
        plan.setFpNumber(reportOrder.getQualify()); //成品数量
        plan.setSpNumber(reportOrder.getDisQua());//半成品数量
        plan.setCreateBy(reportOrder.getReportBy());//入仓人
        plan.setRemark(reportOrder.getRemark());//入仓备注
        Result<Object> reportResult = reportOrderService.insertTbReportOrder(reportOrder);//审核报工
        Result<Object> planResult = tbProdPlanService.updateFinCount(plan);//修改生产数量，跟新增入库记录
        boolean orderResult = orderService.updateOrdMatl(reportOrder.getOrderNumber(), reportOrder.getMatlNumber());//订单号跟物料编号
        //全部成功过才入库成功
        if (reportResult.getCode().equals(ResultEnum.SUCCESS.getCode()) && planResult.getCode().equals(ResultEnum.SUCCESS.getCode()) && orderResult) {
            return ResultUtil.success(ResultEnum.SUCCESS, "入库成功!");
        }
        throw new ServiceException("入库失败!");
    }
}
